﻿global using Microsoft.Data.SqlClient;

namespace MPNet6.Server.Demo.Models;

public static class ClientMessageProcessor
{
    const string MPMsgProjectName = "MP6NetMsg";
    public static string ConnectionString { get; set; } = default!;

    public static List<MPClientMessage> GetMessages()
    {

        try
        {
            using var cn = new SqlConnection(ConnectionString);
            var cmd = cn.CreateCommand();
            cmd.CommandText = $"select top 1 msg from Logs where ProjectName='{MPMsgProjectName}'";
            cn.Open();
            var dr = cmd.ExecuteReader();
            if (dr.Read())
                return JsonSerializer.Deserialize<List<MPClientMessage>>(dr.GetString(0)) ?? new();
        }
        catch (Exception)
        {
        }
        return new();
    }
    public static void SaveMessages(List<MPClientMessage> msgs)
    {

        try
        {
            using var cn = new SqlConnection(ConnectionString);
            var cmd = cn.CreateCommand();
            cmd.CommandText = $"delete logs where ProjectName='{MPMsgProjectName}'; INSERT INTO Logs (ProjectName,Name,LogLevel,Msg,Dt) values('{MPMsgProjectName}','','',@Msgs,getdate())";
            cmd.Parameters.AddWithValue("@Msgs", JsonSerializer.Serialize(msgs));
            cn.Open();
            cmd.ExecuteNonQuery();
        }
        catch (Exception)
        {
        }
    }
}
